<script setup lang="ts">
import { reactive } from 'vue'
import { useUserStore, type Role, type Account } from '@/stores/user'
import { usePerm } from '@/composables/perm'

const store = useUserStore()
const dialog = reactive({ visible: false, editing: false })
const form = reactive<{ id?: number; username: string; password: string; role: Role }>({
  username: '',
  password: '',
  role: 'viewer'
})

const openCreate = () => {
  dialog.visible = true
  dialog.editing = false
  Object.assign(form, { id: undefined, username: '', password: '', role: 'viewer' })
}

const openEdit = (row: Account) => {
  dialog.visible = true
  dialog.editing = true
  Object.assign(form, row)
}

const submit = () => {
  if (!form.username) return
  if (dialog.editing && form.id) {
    store.updateUser(form.id, { username: form.username, password: form.password, role: form.role })
  } else {
    store.createUser({ username: form.username, password: form.password, role: form.role })
  }
  dialog.visible = false
}

const remove = (row: Account) => {
  if (!perm.canManageUsers.value) return
  store.removeUser(row.id)
}

const perm = usePerm()
</script>

<template>
  <div style="padding:16px">
    <el-card>
      <div style="display:flex; justify-content:space-between; align-items:center">
        <div>用户管理</div>
        <el-button type="primary" @click="openCreate">新建用户</el-button>
      </div>
    </el-card>

    <el-card style="margin-top:12px">
      <el-table :data="store.users" stripe>
        <el-table-column prop="id" label="#" width="60" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="role" label="角色" width="120" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="openEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="remove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.editing ? '编辑用户' : '新建用户'" width="420">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role" style="width:200px">
            <el-option label="管理员" value="admin" />
            <el-option label="编辑" value="editor" />
            <el-option label="访客" value="viewer" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible=false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
  
</template>

<style scoped>
</style>


